using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ARF.Web.Utility
{
    public class PageFilterStream : Stream
    {
        private StringBuilder _response = new StringBuilder();
        private Stream _outStream;

        public PageFilterStream(Stream outStream)
        {
            _outStream = outStream;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            _response.Append(Encoding.UTF8.GetString(buffer, offset, count));
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override long Length
        {
            get { return _response.Length; }
        }

        public override void Close()
        {
            PageCleanup.CleanHtml(_response);

            if (_response.Length > 0)
            {
                byte[] arBytes = Encoding.UTF8.GetBytes(_response.ToString());
                _outStream.Write(arBytes, 0, arBytes.Length);
            }

            _outStream.Close();
            //base.Close();
        }
        public override bool CanWrite
        {
            get { return true; }
        }
        public override bool CanRead
        {
            get { return false; }
        }

        public override void SetLength(long value)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanTimeout
        {
            get
            {
                return base.CanTimeout;
            }
        }

        public override long Position
        {
            get
            {
                throw new Exception("The method or operation is not implemented.");
            }
            set
            {
                throw new Exception("The method or operation is not implemented.");
            }
        }

        public override void Flush()
        {
            //_response = new StringBuilder();
            return;
        }

    }
}
